<?php
namespace app\api\controller;

use think\Db;
use think\Exception;

class Order extends BaseController
{
    /**
     * 创建订单
     */
    public function create()
    {
        $this->checkToken();
        
        $member_id = $this->getUserId();
        $type = input('type/s', ''); // 订单类型：membership-会员充值，balance-余额充值，monthly-月租车
        $amount = input('amount/f', 0);
        $item_id = input('item_id/d', 0); // 商品ID（会员等级ID或其他）
        $quantity = input('quantity/d', 1);
        $remark = input('remark/s', '');
        
        if (!$type || !$amount) {
            return $this->renderError('参数错误');
        }
        
        // 验证订单类型
        $allowedTypes = ['membership', 'balance', 'monthly', 'parking'];
        if (!in_array($type, $allowedTypes)) {
            return $this->renderError('订单类型错误');
        }
        
        // 生成订单号
        $order_no = 'ORD' . date('YmdHis') . rand(1000, 9999);
        
        try {
            $order_data = [
                'order_no' => $order_no,
                'member_id' => $member_id,
                'type' => $type,
                'amount' => $amount,
                'original_amount' => $amount,
                'item_id' => $item_id,
                'quantity' => $quantity,
                'status' => 0, // 0-待支付，1-已支付，2-已取消，3-已退款
                'remark' => $remark,
                'created_at' => date('Y-m-d H:i:s')
            ];
            
            $order_id = Db::name('orders')->insertGetId($order_data);
            
            return $this->renderSuccess([
                'order_id' => $order_id,
                'order_no' => $order_no,
                'amount' => $amount,
                'type' => $type
            ]);
        } catch (Exception $e) {
            return $this->renderError('创建订单失败');
        }
    }
    
    /**
     * 获取订单列表
     */
    public function getList()
    {
        $this->checkToken();
        
        $member_id = $this->getUserId();
        $page = input('page/d', 1);
        $limit = input('limit/d', 10);
        $status = input('status/s', 'all'); // all-全部，pending-待支付，paid-已支付，cancelled-已取消
        $type = input('type/s', 'all'); // 订单类型筛选
        
        $where = ['member_id' => $member_id];
        
        // 根据状态筛选
        if ($status !== 'all') {
            switch ($status) {
                case 'pending':
                    $where['status'] = 0;
                    break;
                case 'paid':
                    $where['status'] = 1;
                    break;
                case 'cancelled':
                    $where['status'] = 2;
                    break;
                case 'refunded':
                    $where['status'] = 3;
                    break;
            }
        }
        
        // 根据类型筛选
        if ($type !== 'all') {
            $where['type'] = $type;
        }
        
        $list = Db::name('orders')
            ->where($where)
            ->order('created_at desc')
            ->paginate($limit, false, ['page' => $page]);
        
        // 处理数据
        foreach ($list as &$item) {
            // 处理状态文本
            switch ($item['status']) {
                case 0:
                    $item['status_text'] = '待支付';
                    break;
                case 1:
                    $item['status_text'] = '已支付';
                    break;
                case 2:
                    $item['status_text'] = '已取消';
                    break;
                case 3:
                    $item['status_text'] = '已退款';
                    break;
            }
            
            // 处理类型文本
            switch ($item['type']) {
                case 'membership':
                    $item['type_text'] = '会员充值';
                    break;
                case 'balance':
                    $item['type_text'] = '余额充值';
                    break;
                case 'monthly':
                    $item['type_text'] = '月租车';
                    break;
                case 'parking':
                    $item['type_text'] = '停车费';
                    break;
                default:
                    $item['type_text'] = '其他';
                    break;
            }
            
            // 格式化时间
            $item['created_at_text'] = date('Y-m-d H:i', strtotime($item['created_at']));
            $item['paid_at_text'] = $item['paid_at'] ? date('Y-m-d H:i', strtotime($item['paid_at'])) : '';
        }
        
        return $this->renderSuccess($list);
    }
    
    /**
     * 获取订单详情
     */
    public function getDetail()
    {
        $this->checkToken();
        
        $member_id = $this->getUserId();
        $order_id = input('order_id/d', 0);
        $order_no = input('order_no/s', '');
        
        if (!$order_id && !$order_no) {
            return $this->renderError('参数错误');
        }
        
        $where = ['member_id' => $member_id];
        if ($order_id) {
            $where['id'] = $order_id;
        } else {
            $where['order_no'] = $order_no;
        }
        
        $order = Db::name('orders')->where($where)->find();
        
        if (!$order) {
            return $this->renderError('订单不存在');
        }
        
        // 处理状态文本
        switch ($order['status']) {
            case 0:
                $order['status_text'] = '待支付';
                break;
            case 1:
                $order['status_text'] = '已支付';
                break;
            case 2:
                $order['status_text'] = '已取消';
                break;
            case 3:
                $order['status_text'] = '已退款';
                break;
        }
        
        // 处理类型文本
        switch ($order['type']) {
            case 'membership':
                $order['type_text'] = '会员充值';
                break;
            case 'balance':
                $order['type_text'] = '余额充值';
                break;
            case 'monthly':
                $order['type_text'] = '月租车';
                break;
            case 'parking':
                $order['type_text'] = '停车费';
                break;
            default:
                $order['type_text'] = '其他';
                break;
        }
        
        // 格式化时间
        $order['created_at_text'] = date('Y-m-d H:i:s', strtotime($order['created_at']));
        $order['paid_at_text'] = $order['paid_at'] ? date('Y-m-d H:i:s', strtotime($order['paid_at'])) : '';
        
        return $this->renderSuccess($order);
    }
    
    /**
     * 取消订单
     */
    public function cancel()
    {
        $this->checkToken();
        
        $member_id = $this->getUserId();
        $order_id = input('order_id/d', 0);
        
        if (!$order_id) {
            return $this->renderError('参数错误');
        }
        
        $order = Db::name('orders')
            ->where('id', $order_id)
            ->where('member_id', $member_id)
            ->find();
        
        if (!$order) {
            return $this->renderError('订单不存在');
        }
        
        if ($order['status'] != 0) {
            return $this->renderError('只能取消待支付的订单');
        }
        
        try {
            Db::name('orders')->where('id', $order_id)->update([
                'status' => 2,
                'cancelled_at' => date('Y-m-d H:i:s')
            ]);
            
            return $this->renderSuccess('订单取消成功');
        } catch (Exception $e) {
            return $this->renderError('取消订单失败');
        }
    }
}